package com.jubaozan.service.platform.decorator;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jubaozan.c3.framework.utils.ObjectUtil;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.dao.youme.domain.Activity;
import com.jubaozan.dao.youme.domain.ActivityGoods;
import com.jubaozan.dao.youme.domain.StoreGoods;
import com.jubaozan.dao.youme.service.ActivityGoodsService;
import com.jubaozan.dao.youme.service.ActivityService;
import com.jubaozan.dao.youme.service.StoreGoodsService;
import com.jubaozan.service.platform.constants.GoodsAuditEnum;
import com.jubaozan.service.platform.constants.GoodsStatusEnum;
import com.jubaozan.service.platform.exception.PlatformException;
import com.jubaozan.service.platform.vo.ActivityInfoVO;
import com.jubaozan.service.platform.vo.PlatformActivityVO;
import com.jubaozan.service.platform.vo.StoreGoodsVO;
import com.jubaozan.feign.goods.StoreGoodsFeignService;
import com.jubaozan.feign.goods.vo.GoodsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @ClassName PlatformActivityDecorator
 * @Description 个体平台活动Decorator
 * @Author TanRuixiang
 * @Date 2020/9/23 13:44
 * @Version 1.0
 **/
@Slf4j
@Component
public class PlatformActivityDecorator {

    private final ActivityService activityService;

    private final ActivityGoodsService activityGoodsService;

    private final StoreGoodsService storeGoodsService;


    private final StoreGoodsFeignService storeGoodsFeignService;

    @Autowired
    public PlatformActivityDecorator(ActivityService activityService, ActivityGoodsService activityGoodsService,
                                     StoreGoodsService storeGoodsService, StoreGoodsFeignService storeGoodsFeignService) {
        this.activityService = activityService;
        this.activityGoodsService = activityGoodsService;
        this.storeGoodsService = storeGoodsService;
        this.storeGoodsFeignService = storeGoodsFeignService;
    }

    /**
     * @param storeId: 个体平台ID
     * @param months:  时间区间
     * @return
     * @Author TanRuixiang
     * @Description 获取时间范围的活动信息
     * @Date 2020年09月23日 14:19
     **/
    public List<Activity> getActivitysByStoreId(Long storeId, Integer months) {
        QueryWrapper<Activity> qw = new QueryWrapper<>();
        qw.lambda().eq(Activity::getStoreId, storeId).eq(Activity::getMonths, months);
        return activityService.list(qw);
    }

    /**
     * @param storeId: 个体平台ID
     * @param days:    日  20200922
     * @return
     * @Author TanRuixiang
     * @Description 获取到活动集合信息
     * @Date 2020年09月23日 14:18
     **/
    public List<PlatformActivityVO> getListByDay(Long storeId, Integer days,Long userId) {
        QueryWrapper<Activity> qw = new QueryWrapper<>();
        qw.lambda().eq(Activity::getStoreId, storeId).eq(Activity::getDays, days);
        List<Activity> list = activityService.list(qw);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<PlatformActivityVO> resultList = new ArrayList<>(list.size());
        list.forEach(a -> {
            PlatformActivityVO paVO = new PlatformActivityVO();
            BeanUtils.copyProperties(a, paVO);
            paVO.setGoodsName(this.getGoodsNameByActivityId(a.getId(), storeId,userId));
            resultList.add(paVO);
        });
        return resultList;
    }

    /**
     * @param activityId: 活动ID
     * @return
     * @Author TanRuixiang
     * @Description 通过活动ID获取到商品集合并封装商品名称
     * @Date 2020年09月23日 14:18
     **/
    private String getGoodsNameByActivityId(Long activityId, Long storeId,Long userId) {
        QueryWrapper<ActivityGoods> qw = new QueryWrapper<>();
        qw.lambda().eq(ActivityGoods::getActivityId, activityId);
        List<ActivityGoods> goodsList = activityGoodsService.list(qw);
        if (CollectionUtils.isEmpty(goodsList)) {
            return null;
        }
        List<Long> goodsIds = new ArrayList<>(goodsList.size());
        goodsList.forEach(a -> {
            goodsIds.add(a.getGoodsId());
        });
        //通过商品ID集合获取到商品名称
        List<com.jubaozan.feign.goods.vo.StoreGoodsVO> list = this.getGoodsListByIds(goodsIds, storeId,userId);
        if (!CollectionUtils.isEmpty(list)) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getGoodsName());
                if (i != list.size() - 1) {
                    sb.append("/");
                }
            }
            return sb.toString();
        }
        return null;
    }

    /**
     * @param storeId:
     * @return
     * @Author TanRuixiang
     * @Description 通过门店ID获取到门店下面的商品集合
     * @Date 2020年09月24日 15:15
     **/
    public List<StoreGoodsVO> getGoodsListById(Long storeId,Long userId) {
        QueryWrapper<StoreGoods> qw = new QueryWrapper<>();
        qw.lambda().eq(StoreGoods::getStoreId, storeId).orderByDesc(StoreGoods::getCreateAt);
        List<StoreGoods> list = storeGoodsService.list(qw);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<Long> goodsIds = new ArrayList<>(list.size());
        list.forEach(a -> {
            goodsIds.add(a.getGoodsId());
        });
        List<com.jubaozan.feign.goods.vo.StoreGoodsVO> goodsList = this.getGoodsListByIds(goodsIds, storeId,userId);
        if (!CollectionUtils.isEmpty(goodsList)) {
            //根据商品ID获取到商品的详细信息
            //根据商品的详细信息计算商品的利润率,可赚的最小金额和最大金额
            List<StoreGoodsVO> goodsVOList = new ArrayList<>(goodsList.size());
            goodsList.forEach(a -> {
                this.calculationProfit(a, goodsVOList);
            });
            logger.info("获取到个体平台下可分配的商品集合:{}", JSONObject.toJSONString(goodsVOList));
            return goodsVOList;
        }
        return Collections.emptyList();

    }

    private BigDecimal calcPrice(double retailPrice, double costPrice){
        return new BigDecimal(retailPrice - costPrice);
    }

    private BigDecimal calcPrice(BigDecimal retailPrice, BigDecimal costPrice){
        return retailPrice.subtract(costPrice);
    }

    /**
     * @param a:
     * @param goodsVOList:
     * @return
     * @Author TanRuixiang
     * @Description 计算可赚取的利润
     * @Date 2020年09月28日 13:52
     **/
    private void calculationProfit(com.jubaozan.feign.goods.vo.StoreGoodsVO a, List<StoreGoodsVO> goodsVOList) {
        StoreGoodsVO goodsVO = new StoreGoodsVO();
        BeanUtils.copyProperties(a, goodsVO);

        retailPriceToDouble(goodsVO,a);
        if (CollectionUtils.isEmpty(a.getGoodsSkus())) {
            //最大零售价-最大批发价
            BigDecimal maxMakePrice = calcPrice(a.getRetailPrice(),a.getMaxCostPrice());
            maxMakePrice = maxMakePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            goodsVO.setMaxMakePrice(maxMakePrice);
            //最小零售价-最大批发价
            BigDecimal minMakePrice = calcPrice(a.getRetailPrice(),a.getMinCostPrice());
            minMakePrice = minMakePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            goodsVO.setMinMakePrice(minMakePrice);
        } else {
            //最大零售价-最大批发价
            BigDecimal maxMakePrice = calcPrice(a.getMaxRetailPrice(),a.getMaxCostPrice());
            maxMakePrice = maxMakePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            goodsVO.setMaxMakePrice(maxMakePrice);
            //最小零售价-最大批发价
            BigDecimal minMakePrice = calcPrice(a.getMinRetailPrice(),a.getMinCostPrice());
            minMakePrice = minMakePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            goodsVO.setMinMakePrice(minMakePrice);
        }

        //判断商品是否上架或下架或审核状态
        if(a.getStatus().equals(GoodsStatusEnum.GOODS_HAS_PUBLISH.status()) &&
                a.getAuditStatus().equals(GoodsAuditEnum.YES_AUDIT.status())){
            goodsVO.setFinalStatus(GoodsStatusEnum.GOODS_HAS_PUBLISH.status());
        }else{
            goodsVO.setFinalStatus(GoodsStatusEnum.NOTGOODS_HAS_PUBLISH.status());
        }
        goodsVOList.add(goodsVO);
    }

    private void retailPriceToDouble(StoreGoodsVO storeGoodsVO,com.jubaozan.feign.goods.vo.StoreGoodsVO item){
        BigDecimal min = new BigDecimal(item.getMinRetailPrice());
        min = min.setScale(2,BigDecimal.ROUND_HALF_UP);
        storeGoodsVO.setMinRetailPrice(min);
        BigDecimal max = new BigDecimal(item.getMaxRetailPrice());
        max = max.setScale(2,BigDecimal.ROUND_HALF_UP);
        storeGoodsVO.setMaxRetailPrice(max);

        storeGoodsVO.setMaxCostPrice(new BigDecimal(item.getMaxCostPrice()).setScale(2,BigDecimal.ROUND_HALF_UP));
        storeGoodsVO.setMinCostPrice(new BigDecimal(item.getMinCostPrice()).setScale(2,BigDecimal.ROUND_HALF_UP));
        storeGoodsVO.setMaxProfit(new BigDecimal(item.getMaxProfit()).setScale(2,BigDecimal.ROUND_HALF_UP));
    }
    /**
     * @param skuVOList:
     * @return
     * @Author TanRuixiang
     * @Description 获取最大的零售价
     * @Date 2020年10月07日 4:05
     **//*
    private Double getMaxPrice(List<GoodsVO.GoodsSkuVO> skuVOList) {
        Collections.sort(skuVOList, new Comparator<GoodsVO.GoodsSkuVO>() {
            @Override
            public int compare(GoodsVO.GoodsSkuVO o1, GoodsVO.GoodsSkuVO o2) {
                return o1.getRetailPrice().compareTo(o2.getRetailPrice());
            }
        });
        return skuVOList.get(0).getRetailPrice();
    }

    *//**
     * @param skuVOList:
     * @return
     * @Author TanRuixiang
     * @Description 获取最小的零售价
     * @Date 2020年10月07日 4:06
     **//*
    private Double getMinPrice(List<GoodsVO.GoodsSkuVO> skuVOList) {
        Collections.sort(skuVOList, new Comparator<GoodsVO.GoodsSkuVO>() {
            @Override
            public int compare(GoodsVO.GoodsSkuVO o1, GoodsVO.GoodsSkuVO o2) {
                return o2.getRetailPrice().compareTo(o1.getRetailPrice());
            }
        });
        return skuVOList.get(0).getRetailPrice();
    }*/

    /**
     * @param goodsIds: 商品ID集合
     * @return
     * @Author TanRuixiang
     * @Description 通过商品ID集合查询到商品信息集合
     * @Date 2020年09月25日 16:46
     **/
    public List<com.jubaozan.feign.goods.vo.StoreGoodsVO> getGoodsListByIds(List<Long> goodsIds, Long storeId, Long userId) {
        ResultHolder<List<com.jubaozan.feign.goods.vo.StoreGoodsVO>> holder = storeGoodsFeignService.listGoodsByIds(goodsIds, storeId,userId);
        if (holder.isSuccess()) {
            return holder.getBody();
        }
        return Collections.emptyList();
    }

    /**
     * @param activityInfoVO:
     * @return
     * @Author TanRuixiang
     * @Description 创建活动, 活动关联的商品
     * @Date 2020年09月23日 15:32
     **/
    @Transactional(propagation = Propagation.REQUIRED)
    public void add(ActivityInfoVO activityInfoVO) {
        Activity newActivity = packageActivity(activityInfoVO);
        activityService.save(newActivity);
        List<ActivityGoods> list = packageGoodsIds(newActivity,activityInfoVO.getGoodsIds());
        activityGoodsService.saveBatch(list);
    }

    /**
     * 组装活动对象
     *
     * @param activityInfoVO
     * @return
     */
    private Activity packageActivity(ActivityInfoVO activityInfoVO) {
        //开始封装新的活动
        Activity newActivity = new Activity();
        BeanUtils.copyProperties(activityInfoVO, newActivity);
        newActivity.setCreateBy(String.valueOf(activityInfoVO.getUserId()));
        Integer months = Integer.valueOf(DateTimeFormatter.ofPattern("yyyyMM").format(activityInfoVO.getStartTime()));
        newActivity.setMonths(months);
        Integer days = Integer.valueOf(DateTimeFormatter.ofPattern("yyyyMMdd").format(activityInfoVO.getStartTime()));
        newActivity.setDays(days);
        return newActivity;
    }

    /**
     * 组装活动商品关联对象
     * @param newActivity
     * @param goodsIds
     * @return
     */
    private List<ActivityGoods> packageGoodsIds(Activity newActivity,List<Long> goodsIds){
        List<ActivityGoods> list = new ArrayList<>(goodsIds.size());
        goodsIds.forEach(a -> {
            ActivityGoods goods = new ActivityGoods();
            goods.setGoodsId(a);
            goods.setActivityId(newActivity.getId());
            list.add(goods);
        });
        return list;
    }





    /**
     * @param storeId: 平台ID
     * @param date:    时间
     * @return
     * @Author TanRuixiang
     * @Description 根据时间获取这个时间区间是否有活动
     * @Date 2020年09月29日 9:31
     **/
    public Activity getActivityByTime(Long storeId, LocalDateTime startTime, LocalDateTime endTime) {
        Activity activity = null;
        QueryWrapper<Activity> qw = new QueryWrapper<>();
        qw.lambda().nested(b ->b.between(Activity::getStartTime, startTime, endTime).or().between(Activity::getEndTime, startTime, endTime)).nested(i ->i.eq(Activity::getStoreId,storeId));
        activity = activityService.getOne(qw, false);
        if (ObjectUtil.isEmpty(activity)) {
            QueryWrapper<Activity> qw1 = new QueryWrapper<>();
            qw1.lambda().eq(Activity::getStoreId, storeId).le(Activity::getStartTime, startTime).ge(Activity::getEndTime, endTime);
            activity = activityService.getOne(qw1,false);
        }
        return activity;
    }
}
